package com.yupao.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupao.common.BaseResponse;
import com.yupao.common.ResultUtils;
import com.yupao.exception.BusinessException;
import com.yupao.model.dto.UserLoginDTO;
import com.yupao.model.entity.User;
import com.yupao.model.enums.ErrorCode;
import com.yupao.model.vo.LoginUserVO;
import com.yupao.model.vo.UserVO;
import com.yupao.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
@CrossOrigin(origins = {"http://localhost:5173"}, allowCredentials="true")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 用户注册
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserLoginDTO userLoginDTO){
        //非空
        if (ObjectUtils.isEmpty(userLoginDTO)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginDTO.getUserAccount();
        String userPassword = userLoginDTO.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long result = userService.userRegister(userAccount, userPassword);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginDTO userLoginDTO){
        //非空判断
        if (ObjectUtils.isEmpty(userLoginDTO)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        String userAccount = userLoginDTO.getUserAccount();
        String userPassword = userLoginDTO.getUserPassword();

        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        LoginUserVO loginUserVO = userService.userLogin(userAccount,userPassword);
        return ResultUtils.success(loginUserVO);
    }

    @GetMapping("/current")
    public BaseResponse<LoginUserVO> currentUser(){
        LoginUserVO loginUserVO = userService.getLoginUser();
        if (ObjectUtils.isEmpty(loginUserVO)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return ResultUtils.success(loginUserVO);
    }

    /**
     * 根据标签搜索用户
     * @param tagList
     * @return
     */
    @GetMapping("/search/tags")
    public BaseResponse<List<User>> searchUserByTags(@RequestParam(required = false) List<String> tagList){
        //非空判断
        if (CollectionUtils.isEmpty(tagList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<User> userList = userService.searchUserByTags(tagList);

        return ResultUtils.success(userList);
    }

    /**
     * 修改用户
     * @param user
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Integer> updateUser(@RequestBody User user){
        //非空判断
        if (ObjectUtils.isEmpty(user)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Integer result = userService.updateUser(user);
        return ResultUtils.success(result);
    }

    /**
     * 推荐用户
     * @return
     */
    @GetMapping("/recommend")
    public BaseResponse<List<LoginUserVO>> recommendUsers(int pageSize, int pageNum){
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        LoginUserVO loginUser = userService.getLoginUser();
        //设置redis中的key
        String keyStr = String.format("yupao:user:%s", loginUser.getId());

        //redis中存在缓存
        List<LoginUserVO> userVOList = (List<LoginUserVO>) valueOperations.get(keyStr);
        if (ObjectUtils.isNotEmpty(userVOList)) {
            return ResultUtils.success(userVOList);
        }

        //redis不存在缓存
        Page<User> userPage = userService.page(new Page<>(pageSize, pageNum));
        List<User> userList = userPage.getRecords();
        List<LoginUserVO> loginUserVOList = new ArrayList<>();
        for (User user : userList) {
            LoginUserVO loginUserVO = new LoginUserVO();
            BeanUtils.copyProperties(user, loginUserVO);
            loginUserVOList.add(loginUserVO);
        }

        //将数据存入缓存
        valueOperations.set(keyStr,loginUserVOList,300000, TimeUnit.MILLISECONDS);

        return ResultUtils.success(loginUserVOList);
    }

    /**
     * 推荐用户
     * @param num
     * @return
     */
    @GetMapping("/match")
    public BaseResponse<List<UserVO>> matchUsers(long num){
        if (num <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        List<UserVO> userVOList = userService.matchUsers(num);

        return ResultUtils.success(userVOList);

    }

}
